'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: stu_code.py
* @Time: 2025/11/5
* @All Rights Reserve By Brtc
'''
import dotenv
import requests
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.tools import BaseTool
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field

import json
import os
from typing import Type, Any

dotenv.load_dotenv()
class GaodeWeatherSchema(BaseModel):
    city:str = Field(description="需要查询天气的城市，如：广州")

class GaodeWeatherTool(BaseTool):
    """根据传入的城市名称运行调用API 获取传入城市的天气预报信息"""
    name:str = "gaode_weather_tool"
    description:str = "当你想查询天气都时候可以用这个工具"
    args_schema: Type[BaseModel] = GaodeWeatherSchema

    def _run(self, *args:Any, **kwargs:Any) -> Any:
        print("======================================")
        try:
            gaode_api_key = os.getenv("GAODE_API_KEY")
            gaode_api_url = os.getenv("GAODE_BASE_URL")
            if not gaode_api_key or not gaode_api_url:
                return f"请配置正确的高德API KEY 和 URL"
            else:
                #1、从参数中获取城市
                city = kwargs.get("city")
                #2、行政区域查询
                session = requests.session()
                city_response = session.request(
                    method = "GET",
                    url = f"{gaode_api_url}/config/district?key={gaode_api_key}&keywords={city}&subdistrict=0",
                    headers = {"Content-Type":"application/json;charset=utf-8"}
                )
                city_response.raise_for_status()
                city_data =city_response.json()
                print(city_data)
                if city_data.get("info") == "OK":
                    ad_code = city_data.get("districts")[0]["adcode"]
                    weather_info = session.request(
                        method="GET",
                        url=f"{gaode_api_url}/weather/weatherInfo?key={gaode_api_key}&city={ad_code}&extensions=all",
                    )
                    print(weather_info)
                    weather_info.raise_for_status()
                    weather_data = weather_info.json()
                    print(weather_data)
                    if weather_data.get("info") == "OK":
                        return json.dumps(weather_data)
                return f"获取{city}天气预报失败"
        except Exception as e:
            return f"获取天气失败"

gaode_weather = GaodeWeatherTool()


# 构建提示词
prompt = ChatPromptTemplate.from_messages([
    ("human",[
        {"type":"text","text":"请识别图片中的城市"},
        {"type":"image_url","image_url":"{image_url}"}
    ]

    ),
])

weather_prompt = ChatPromptTemplate.from_template(
    """
    请传递城市的天气预报信息，并以用户友好的方式输出！
    <weather>
    {weather}
    </weather>
    """
)

# 构建llm并绑定工具
llm = ChatOpenAI(model="gpt-4o-mini")
llm_with_tools = llm.bind_tools([GaodeWeatherTool()],tool_choice="gaode_weather_tool")

# 创建链应用并执行
chain = (
    {
        "weather":(
            {"image_url":RunnablePassthrough()}
            |prompt
            |llm_with_tools
            |(lambda msg:msg.tool_calls[0]["args"])
            |GaodeWeatherTool()
        )
    }|weather_prompt|llm|StrOutputParser()
)

print(chain.invoke("https://img1.baidu.com/it/u=1224667772,1366084778&fm=253&app=138&f=JPEG?w=800&h=1422"))